package idoc.handOn.workshop.service.impl;

import idoc.handOn.workshop.model.Word;
import idoc.handOn.workshop.service.WordService;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class WordServiceImpl implements WordService {
	

	@Override
	public Set<Word> getWords(File file) {
		Set<Word> words = new HashSet<Word>();
		BufferedReader myInput = null;
		InputStreamReader inputStreamReader = null;
		try {
			String line = "";
			FileInputStream fin = new FileInputStream(file);
			inputStreamReader = new InputStreamReader(fin);
			myInput = new BufferedReader(inputStreamReader);
			while ((line = myInput.readLine()) != null) {
				Word word = new Word();
				word.setWord(line);
				words.add(word);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			closeBuffers(myInput, inputStreamReader);
		}

		return words;
	}

	public void closeBuffers(BufferedReader myInput, InputStreamReader inputStreamReader) {
		if (myInput != null) {
			try {
				myInput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (inputStreamReader != null) {
			try {
				inputStreamReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public List<Word> loadCommonWords(List<Set<Word>> words) {
		List<Word> result = new ArrayList<Word>();
		Map<Word, Integer> wordsMap = new HashMap<Word, Integer>();
		if (words != null && !words.isEmpty()) {
			for (Set<Word> list : words) {
				for (Word word : list) {
					if (!wordsMap.containsKey(word)) {
						wordsMap.put(word, 1);
					}
					else {
						result.add(word);
					}
				}
			}
		}
		return result;
	}
}
